using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Collections;
using System.Text;

public class ImageGenerator : MonoBehaviour
{
    public static ImageGenerator Instance; // Singleton instance

    private string endpoint => APIConfig.Instance.imageEndpoint;
    private string apiKey => APIConfig.Instance.imageApiKey;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject); // keep across scenes
        }
        else
        {
            Destroy(gameObject);
        }
    }

    // Generate scene background image (Texture2D)
    public IEnumerator GenerateSceneImage(string prompt, System.Action<Texture2D> onComplete)
    {
        string jsonData = "{\"prompt\":\"" + prompt + "\", \"size\":\"1536x1024\", \"quality\":\"high\", \"output_format\":\"png\", \"n\":1}";
        Debug.Log("Scene image request: " + jsonData);

        byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);

        using (UnityWebRequest request = new UnityWebRequest(endpoint, "POST"))
        {
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Authorization", "Bearer " + apiKey);

            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                var responseText = request.downloadHandler.text;
                Debug.Log("Scene image response: " + responseText);

                ImageResponse resp = JsonUtility.FromJson<ImageResponse>(responseText);

                byte[] imageBytes = Convert.FromBase64String(resp.data[0].b64_json);
                Texture2D tex = new Texture2D(2, 2);
                tex.LoadImage(imageBytes);

                onComplete?.Invoke(tex);
            }
            else
            {
                Debug.LogError("Scene image error: " + request.error);
                Debug.LogError("Response: " + request.downloadHandler.text);
                onComplete?.Invoke(null);
            }
        }

        //if both images already loaded set their anim bool Loaded to false and delete after 3 seconds?
    }

    // Generate NPC portrait image (Sprite)
    public IEnumerator GenerateNpcImage(string prompt, System.Action<Sprite> onComplete)
    {
        string jsonData = "{"
            + "\"prompt\":\"" + prompt + "\","
            + "\"size\":\"1024x1024\","
            + "\"quality\":\"high\","
            + "\"output_format\":\"png\","
            + "\"background\":\"transparent\","
            + "\"n\":1}";

        Debug.Log("NPC image request: " + jsonData);
        
        byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);

        using (UnityWebRequest request = new UnityWebRequest(endpoint, "POST"))
        {
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Authorization", "Bearer " + apiKey);

            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                var responseText = request.downloadHandler.text;
                Debug.Log("NPC image response: " + responseText);

                ImageResponse resp = JsonUtility.FromJson<ImageResponse>(responseText);

                byte[] imageBytes = Convert.FromBase64String(resp.data[0].b64_json);
                Texture2D tex = new Texture2D(2, 2, TextureFormat.RGBA32, false);
                tex.LoadImage(imageBytes, true);

                // Convert to sprite
                Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
                onComplete?.Invoke(sprite);
            }
            else
            {
                Debug.LogError("NPC image error: " + request.error);
                Debug.LogError("Response: " + request.downloadHandler.text);
                onComplete?.Invoke(null);
            }
        }

        //if both images already loaded set their anim bool Loaded to false and delete after 3 seconds?
    }


    [System.Serializable]
    public class ImageResponse
    {
        public Data[] data;
    }

    [System.Serializable]
    public class Data
    {
        public string b64_json;
    }
}
